﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Anticheat.Math
{
    /// <summary>
    /// Integer protected from ArtMoney abuse
    /// </summary>
    public class SecureInteger
    {
        private static readonly Random random = new Random();
        public SecureInteger(int initial)
        {
            Secret = new IntWrap(random.Next());
            Value1 = new IntWrap(initial ^ Secret.Value);
            Value2 = new IntWrap(initial ^ Secret.Value);
        }

        private readonly IntWrap Value1;
        private readonly IntWrap Value2;
        private readonly IntWrap Secret;
        public bool IsValid
        {
            get
            {
                return Value1.Value == Value2.Value;
            }
        }
        public static implicit operator SecureInteger(int val)
        {
            return new SecureInteger(val);
        }
        public static implicit operator int(SecureInteger val)
        {
            if (val.IsValid)
            {
                return val.Value1.Value ^ val.Secret.Value;
            }
            else
            {
                return random.Next();
            }
        }
        public override string ToString()
        {
            return ((int)this).ToString();
        }
        public override int GetHashCode()
        {
            return ((int)this);
        }

        public bool Equals(SecureInteger other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            return ((int)other).Equals((int)this);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            if (ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj.GetType() != typeof(SecureInteger))
            {
                return false;
            }
            return Equals((SecureInteger)obj);
        }

        public static bool operator ==(SecureInteger left, SecureInteger right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(SecureInteger left, SecureInteger right)
        {
            return !Equals(left, right);
        }
    }
}
